<template>
	<div class="permi_checkbox">
		<el-checkbox :indeterminate="isIndeterminate" v-model="allChecked" @change="handleCheckAllChange">{{ title || '全选' }}</el-checkbox>
		<el-checkbox-group v-model="checkedButton" @change="handleCheckedChange">
			<el-checkbox v-for="(item, index) in data" :key="index" :label="item.id" :disabled="item.isSelect === '1'">
				{{ item.name }}
			</el-checkbox>
		</el-checkbox-group>
	</div>
</template>

<script>
export default {
	props: {
		value: { type: Array, default: () => [] },
		title: String,
		data: { type: Array, default: () => [] }
	},
	data() {
		return {
			allChecked: false,
			checkedButton: this.value,
			isIndeterminate: false
		};
	},
	computed: {
		defaultChecked() {
			return this.data.filter((item) => item.isSelect === '1').map((item) => item.id);
		}
	},
	watch: {
		value(data) {
			this.checkedButton = data;
		},
		checkedButton(data) {
			this.$emit('input', data);
		}
	},
	mounted() {
		this.isIndeterminate = this.checkedButton.length > 0 && this.checkedButton.length < this.data.length;
	},
	methods: {
		handleCheckAllChange(val) {
			this.checkedButton = val ? this.data.map((item) => item.id) : this.defaultChecked;
			this.isIndeterminate = this.checkedButton.length > 0 && this.checkedButton.length < this.data.length;
		},
		handleCheckedChange(data) {
			let checkedCount = data.length;
			this.allChecked = checkedCount === this.data.length;
			this.isIndeterminate = checkedCount > 0 && checkedCount < this.data.length;
		}
	}
};
</script>

<style lang="scss" scoped>
.permi_checkbox {
	padding: 10px 15px;
	margin-bottom: 16px;
	background-color: var(--primary-background-plain-disabled);
	.el-checkbox {
		padding: 11px 0;
	}
}
</style>
